package http_proxy_middleware

import (
	"fmt"
	"gitee.com/zhoulvvv/my_go_gateway/dao"
	"gitee.com/zhoulvvv/my_go_gateway/middleware"
	"gitee.com/zhoulvvv/my_go_gateway/public"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
)

// 租户限流
func HTTPJwtFlowLimitModeMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取租户信息
		appInterface, ok := c.Get("app")
		if !ok {
			c.Next()
			return
		}
		app := appInterface.(*dao.App)
		appQps := float64(app.Qps)
		// 如果租户限流QPS是0就表示无限制
		if appQps > 0 {
			// 租户限流，根据租户下不同的访问IP进行限流
			serverLimiter, err := public.FlowLimiterHandler.GetLimiter(
				public.FlowAppPrefix+app.AppId+"_"+c.ClientIP(),
				appQps)
			if err != nil {
				middleware.ResponseError(c, 8001, errors.New("获取租户限流器失败："+err.Error()))
				c.Abort()
				return
			}
			if !serverLimiter.Allow() {
				middleware.ResponseError(c, 8001, errors.New(fmt.Sprintf("租户限流中，每秒最大QPS：%v，限流IP：%s", appQps, c.ClientIP())))
				c.Abort()
				return
			}
		}
		c.Next()
	}
}
